package com.jihu.leetcode.arrays;

import java.util.*;

/**
 * leetcode 15.三叔之和
 * @author jihu
 * @date 2021/8/25
 */
public class ThreeSum {

    //方法一：暴力法  还需要去重 时间复杂度n的三次方以上
    public static List<List<Integer>> threeSum1(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = i + 1; j < nums.length - 1 ; j++) {
                for (int k = j + 1; k < nums.length ; k++) {
                    if(nums[i]+nums[j]+nums[k] == 0){
                        results.add(Arrays.asList(nums[i],nums[j],nums[k]));
                    }
                }

            }
        }
        return results;
    }

    //方法二：使用哈希表保存结果
    public static List<List<Integer>> threeSum2(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();

        Map<Integer,List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int thatNum = 0 - nums[i];
            if(map.containsKey(thatNum)){
                List<Integer> tempList = new ArrayList<>(map.get(thatNum));
                tempList.add(nums[i]);
                results.add(tempList);
            }

            for (int j = 0; j < i ; j++) {
                int newKey = nums[i] + nums[j];
                if(!map.containsKey(newKey)){
                    List<Integer> tempList = new ArrayList<>();
                    tempList.add(nums[i]);
                    tempList.add(nums[j]);
                    map.put(newKey,tempList);
                }

            }

        }

        return results;
    }

    //方法三：双指针法
    public static List<List<Integer>> threeSum(int[] nums){
        List<List<Integer>> results = new ArrayList<>();
        //先排序
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] > 0) break;
            //前一个数与后一个数相等 跳过
            if(i > 0 && nums[i] == nums[i-1]) continue;

            int leftPoint = i + 1;
            int rightPoint = nums.length - 1;
            while (leftPoint < rightPoint){
                int sum  = nums[i] + nums[leftPoint] + nums[rightPoint];
                if(0 == sum){
                    results.add(Arrays.asList(nums[i] , nums[leftPoint] , nums[rightPoint]));

                    leftPoint ++ ;
                    rightPoint --;

                    while (leftPoint < rightPoint && nums[leftPoint] == nums[leftPoint - 1]) leftPoint ++;
                    while (leftPoint < rightPoint && nums[rightPoint] == nums[rightPoint + 1]) rightPoint --;
                }else if(sum < 0) leftPoint ++;
                else rightPoint --;
            }
        }
        return results;
    }


    public static void main(String[] args) {
        int[] input = new int[]{-1,0,1,2,-1,-4};
        List<List<Integer>> lists = threeSum(input);
        lists.forEach(System.out::println);

    }

}
